package com.situ.interceptor;

import cn.hutool.core.util.StrUtil;
import com.situ.config.JwtProperties;
import com.situ.context.BaseContext;
import com.situ.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        log.info("拦截到路径:{}", request.getRequestURI());
        String token = request.getHeader("token");
        if (StrUtil.isBlankIfStr(token)) {
            log.info("空token登录,已拦截");
            response.sendRedirect("/web/login.html");
            return false;
        }
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            log.info("解析到的claims:{}",claims);
            Integer userId = (Integer) claims.get("userId");
            log.info("当前员工id：{}", userId);
            BaseContext.setCurrentId(userId);
        } catch (Exception e) {
            log.info("jwt校验不通过,已拦截");
            response.setStatus(401);
            response.sendRedirect("/web/login.html");
            return false;
        }
        return true;
    }
}
